import React, {Component} from 'react'
import PropTypes from 'prop-types';
/*引入connect()函数用于链接UI组件和容器组件*/
import {connect} from "react-redux"
/*引入创建action的函数*/
import {createDeleteTodoAction, createChangeTodoDoneAction} from "../../../store/actions/actions";
import "./Item.css"
import {changeTodoDone} from "../../../store/constants/constants";
import store from "../../../store/store";

class Item extends Component {
    static propTypes = {
        todo: PropTypes.object.isRequired
    }

    render() {
        const {todo} = this.props
        return (
            <div className='item'>
                <span className='left'>
                    <input type="checkbox" checked={todo.done} onChange={(event) => this.changeTodoDone(todo.id, event.target.checked)}/>
                    <span className='text'>{todo.name}</span>
                </span>
                <button className="layui-btn  layui-bg-red layui-btn-sm" onClick={() => this.clickHandle(todo)}>删除</button>
            </div>
        )
    }

    clickHandle = (todo) => {
        this.props.deleteTodo(todo.id)
    }
    changeTodoDone = (id, done) => {
        this.props.changeTodoDone(id, done)
    }

    componentDidMount() {
        store.subscribe(() => {
            this.forceUpdate()
        })
    }
}

/*stateToProps是一个函数，这个函数需要返回一个对象（用于将store中state映射到组件中的props中*/
const mapStateToProps = (state) => {
    return {}
}
/*dispatchToProps是一个函数，这个函数需要返回一个对象（用于将store中dispatch映射到组件中的props中*/
const mapDispatchToProps = (dispatch) => {
    return {
        deleteTodo: (id) => dispatch(createDeleteTodoAction(id)),
        changeTodoDone: (id, done) => dispatch(createChangeTodoDoneAction({id, done}))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Item)
